package com.xzakota.minesweeper.widget.text;

import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.*;

/**
 * 可输入文本域
 *
 * @author Xzakota
 */
public class InputTextField extends JPanel {
    private final JLabel tagLabel;
    private final JTextComponent textField;
    private final JTextPane hintLabel;

    public InputTextField() {
        this(null, false);
    }

    public InputTextField(String tagText, boolean isPasswordField) {
        setLayout(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();

        tagLabel = new JLabel();
        setTagText(tagText);
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.LINE_START;
        add(tagLabel, gbc);

        if (isPasswordField) {
            textField = new JPasswordField();
        } else {
            textField = new JTextField();
        }
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.weightx = 1.0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        add(textField, gbc);

        hintLabel = new JTextPane();
        hintLabel.setOpaque(false);
        hintLabel.setEditable(false);
        hintLabel.setVisible(false);
        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.weightx = 1.0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(1, 0, 0, 0);
        add(hintLabel, gbc);

        setOpaque(false);
        setBorder(BorderFactory.createEmptyBorder(0, 2, 2, 2));
    }

    public void setTagText(String text) {
        tagLabel.setText(text);
    }

    public void setTagFont(Font font) {
        tagLabel.setFont(font);
    }

    public String getFieldText() {
        return textField.getText();
    }

    public void setFieldText(String text) {
        textField.setText(text);
    }

    public void setFieldEditable(Boolean editable) {
        textField.setEditable(editable);
    }

    public void setFieldFont(Font font) {
        textField.setFont(font);
    }

    public void setAllFont(Font font) {
        tagLabel.setFont(font);
        textField.setFont(font);
    }

    public void setHintText(String text) {
        hintLabel.setText(text);
        hintLabel.setVisible(true);
    }

    public void setHintText(String text, Color color) {
        hintLabel.setText(text);
        hintLabel.setForeground(color);
        hintLabel.setVisible(true);
    }

    public void appendHintText(String text) {
        setHintText(text + hintLabel.getText());
    }

    @Override
    public void requestFocus() {
        textField.grabFocus();
        textField.requestFocus();
    }
}
